package com.zh.filetransport.indicator.impl;

import com.zh.filetransport.indicator.ProgressIndicator


class ConsoleProgressIndicator : ProgressIndicator {
    private var start = 0
    private var name = "" //文件名
    private var value = 0f //进度值
    private var transferredSize: Long = 0 //已传输的字节数
    private lateinit var builder: CharArray

    init {
        reset()
    }

    private fun reset() {
        builder = CharArray(TOTAL) { INCOMPLETE }
        name = ""
        start = 0
        value = 0f
    }

    companion object {
        private const val INCOMPLETE = '░'
        private const val COMPLETE = '█'
        private const val TOTAL = 50
    }

    override fun bind(id: String, fileName: String, isReceive: Boolean) {
        this.name = fileName
    }

    override fun accept(transferredSize: Long, fileSize: Long) {
        if (fileSize == 0L) return

        //为了保证进度为100%时只打印一次
        if (this.transferredSize < transferredSize) {
            this.value = (transferredSize.toDouble() / fileSize).coerceAtMost(1.0).toFloat()
            printProgress()
        } else {
            println() //换行，不能省
        }
        this.transferredSize = transferredSize
    }

    private fun printProgress() {
        val point = (value * TOTAL).toInt().coerceAtMost(TOTAL)
        for (i in start until point) {
            builder[i] = COMPLETE
        }
        start = point

        val progressBar = "\r${builder.concatToString()}"
        val percent = String.format(" (%d%%) %s", point * 2, name)
        print(progressBar + percent)
        System.out.flush()
    }
}
